'use strict';

const Service = require('egg').Service;
const Wishlist = require('../model/wishlist');
const City = require('../model/city');

class WishlistService extends Service {
  /**
   * 获取用户心愿单城市ID列表
   * @param {number} userId
   * @returns {Promise<number[]>}
   */
  async listByUser(userId) {
    const rows = await Wishlist.findAll({
      where: { user_id: userId },
      attributes: ['city_id'],
      order: [['updated_at', 'DESC']],
    });
    return rows.map(r => r.city_id);
  }

  /**
   * 添加到心愿单
   * @param {number} userId
   * @param {number} cityId
   * @returns {Promise<boolean>}
   */
  async add(userId, cityId) {
    // 可选：校验城市是否存在
    const city = await City.findByPk(cityId);
    if (!city) return false;

    await Wishlist.findOrCreate({
      where: { user_id: userId, city_id: cityId },
      defaults: { user_id: userId, city_id: cityId },
    });
    return true;
  }

  /**
   * 从心愿单移除
   * @param {number} userId
   * @param {number} cityId
   * @returns {Promise<boolean>}
   */
  async remove(userId, cityId) {
    const affected = await Wishlist.destroy({ where: { user_id: userId, city_id: cityId } });
    return affected > 0;
  }
}

module.exports = WishlistService;